//
//  CubeWebViewController.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-9.
//
//

#import "CubeWebViewController.h"
#import <chameleon-ios-sdk/CApplication.h>
#import "CubeModule.h"
#import "DataCenter+Cube.h"
#import "IsolatedStorageFile+CubeLogic.h"
#import <MainModuleSDK/MainUtils.h>
#import <SVProgressHUD/SVProgressHUD.h>

@interface CubeWebViewController ()
-(void)redirectToCubeMainPage;
-(void)loginSuccess;

@property(nonatomic,strong) CCordovaViewController* subContentView;

@end

@implementation CubeWebViewController{
    UIButton* closeButton;
}

-(id)init{
    self=[super init];
    if(self){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"CubeAuth_Success" object:nil];
        
    }
    
    return self;
}

- (void)viewDidLoad{
//    self.view.backgroundColor=  [UIColor colorWithRed:70/255.0 green:135/255.0 blue:199/255.0 alpha:1];

    if([self.identifier length]>0){
        NSString* path=[IsolatedStorageFile cubeModuleIdentifierMainPage:self.identifier];
        if([self.params objectForKey:@"moduleUrl"]!=nil){
            //path=[path stringByAppendingFormat:@"?%@",[self.params objectForKey:@"moduleUrl"]];
            UIAlertView* alert=[[UIAlertView alloc] initWithTitle:@"获取到的参数" message:[self.params objectForKey:@"moduleUrl"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        
        NSURL* url=[NSURL fileURLWithPath:path];
        [self loadFilePageWithFileUrl:url];
    }
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    
    closeButton=[UIButton buttonWithType:UIButtonTypeCustom];
    UIImage* img=[UIImage imageNamed:@"Module.bundle/images/gohome.png"];
    [closeButton setImage:img forState:UIControlStateNormal];
    
    closeButton.frame=CGRectMake(0.0f, self.view.frame.size.height-img.size.height*2.0f, img.size.width*2.0f, img.size.height*2.0f);
    [closeButton addTarget:self action:@selector(redirectToCubeMainPage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeButton];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.subContentView setFinishBlock:nil];
    self.subContentView=nil;
}

#pragma mark webvlew delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSURL* url = [request URL];
    NSLog(@"请求页面: %@", url);
    
    if ([[url absoluteString] rangeOfString:@"cube-action"].location != NSNotFound) {
        
        NSRange range = [[url absoluteString] rangeOfString:@"cube-action"];
        NSString *tempaction = [[url absoluteString] substringFromIndex:range.location + range.length + 1];
        NSRange sharp = [tempaction rangeOfString:@"#"];
        NSString *action = tempaction;
        if(sharp.length != 0){
            action = [tempaction substringToIndex:sharp.location];
        }
        
        if ([@"pop" isEqualToString:action]) {
            
            if(![MainUtils isPad]){
                if([self.navigationController.viewControllers count]>2){
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }
            else{
                if([self.navigationController.viewControllers count]>1){
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    if([self.delegate respondsToSelector:@selector(webViewBackClick:)]){
                        [self.delegate webViewBackClick:self];
                    }
                }
            }            
        } else if([@"push" isEqualToString:action]) {
            [[NSURLCache sharedURLCache] removeAllCachedResponses];

            //remove ?cube-action
            url = [NSURL URLWithString:
                   [[url absoluteString] stringByReplacingOccurrencesOfString:@"?cube-action=push" withString:@""]];
            
            NSString *path = url.path;
            NSRange range = [path rangeOfString:@"www/"];
            if(range.location != NSNotFound){
                //                path = [path substringFromIndex:range.location + range.length];
                //                NSRange range2 = [path rangeOfString:@"/"];;
                //                path = [path substringToIndex:range2.location];
                //dispatch_async(dispatch_get_main_queue(), ^{
                //                [OperateLog recordOperateLogWithIdentifier:path];
                //});
            }
            
            NSURLRequest *newRequest = [NSURLRequest requestWithURL:url cachePolicy:[request cachePolicy] timeoutInterval:[request timeoutInterval]];
            
            [self.subContentView setFinishBlock:nil];
            self.subContentView=nil;
            
            CubeWebViewController* controller=[[CubeWebViewController alloc] init];
            controller.delegate=self.delegate;
            controller.rootViewController=self.rootViewController;
            controller.title=self.title;
            self.subContentView=controller;
            
            [controller loadFilePageWithFileUrl:[newRequest URL]];
            [controller startLoadNow];
            
            __block CubeWebViewController* objSelf=self;
            [controller setFinishBlock:^(BOOL success){
                [objSelf.navigationController pushViewController:objSelf.subContentView animated:YES];
                objSelf.subContentView=nil;
            }];
            
        }
        return NO;
    }
    else if ([@"cube://exit" isEqualToString:[url absoluteString]]) {
        if([self.delegate respondsToSelector:@selector(webViewBackClick:)]){
            [self.delegate webViewBackClick:self];
        }
        else{
            [self.navigationController popToViewController:self.rootViewController animated:YES];
        }
        return [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }
    
    NSString *timeSp = [NSString stringWithFormat:@"?date=%ld", (long)[[NSDate date]  timeIntervalSince1970]];
    
    url =  [url URLByAppendingPathComponent:timeSp];
    
    NSURLRequest *newRequest = [NSURLRequest requestWithURL:url cachePolicy:[request cachePolicy] timeoutInterval:[request timeoutInterval]];
    
    return [super webView:webView shouldStartLoadWithRequest:newRequest navigationType:navigationType];
}


#pragma mark method

-(void)redirectToCubeMainPage{
    if([self.delegate respondsToSelector:@selector(webViewBackClick:)]){
        [self.delegate webViewBackClick:self];
    }
    else{
        [self.navigationController popToViewController:self.rootViewController animated:YES];
    }
}

-(void)loginSuccess{
    [self redirectToCubeMainPage];
}

@end

